package practice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/12
 * @VERSION 1.0
 * @DESC
 * CAS:底层硬件代码--基本含义：多个线程执行时只能有一个线程执行成功（
 * 原子性问题：i++ 有读 改 写操作
 * Volatile：内存可见性（线程和主存的内存共享问题）
 *
 * CAS速度很快，Volatile
 */
class CasAlg{
    private int val;//int oldVal,
    private AtomicInteger val2;
    // 加锁
    int get(){return val;}
    // 比较交换
    synchronized int compareAndSwamp(int expectedVal,int newVal){
        int oldVal = val;
        if(oldVal==expectedVal){
            oldVal = newVal;
        }
        return oldVal;
    }
    synchronized boolean compareAndSet(int expectedVal,int newVal){
         return expectedVal==compareAndSwamp(expectedVal,newVal);
    }
}

class Task implements Runnable{
    volatile boolean flag = true;
    @Override
    public void run() {
         while(flag){
             System.out.println("executing...");
             try {
                 TimeUnit.SECONDS.sleep(1);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
    }
}

public class CASVolatileDemo {
    public static void main(String[] args) throws InterruptedException {
        Task task = new Task();
        //task.run();,区分run()与start()
        new Thread(task).start();
        TimeUnit.SECONDS.sleep(3);
        task.flag=false;
    }
}
